package com.cat.binaryTree;

/**
*   @description https://leetcode.cn/problems/binary-tree-pruning/description/
*   @author 曲大人的喵
*   @create 2025/9/14 15:10
*   @since JDK17
*/

public class Solution32 {
    int f(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int l = f(root.left);
        int r = f(root.right);
        if (l == 0) {
            root.left = null;
        }
        if (r == 0) {
            root.right = null;
        }
        return l + r + root.val;
    }

    TreeNode f2(TreeNode root) {
        if (root == null) {
            return null;
        }
        root.left = f2(root.left);
        root.right = f2(root.right);
        if (root.left == null && root.right == null && root.val == 0) {
            return null;
        }

        return root;
    }

    public TreeNode pruneTree(TreeNode root) {
//        if (f(root) == 0) {
//            return null;
//        }
//        return root;
        return f2(root);
    }
}
